
<template>
  <dialog-form
    v-if="visible"
    width="500px"
    title="数据权限"
    :visible="visible"
    :form-attrs="{formData: modalFormData, renderFormItem, formButtons, labelWidth: '110px', isHideButtons}"
    @close="handleClose"
  />
</template>

<script>
import { fetchDropDeptAllList } from '@/api/common/commonDropDown'
import { DialogForm } from '@/components'
import { dataAuthFormItem, formButtons } from './config'

export default {
  name: 'DataAuth',
  components: { DialogForm },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orgList: { // 机构列表
      type: Array,
      default: () => ([])
    },
    modalFormData: { // 数据
      type: Object,
      default: () => ({})
    },
    isHideButtons: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectAttrs: {
        style: { width: '260px' },
        placeholder: '请选择'
      },

      orgId: 0,
      orgIsHide: true,
      deptIsHide: true,
      deptDropList: [], // 部门下拉

      renderFormItem: [],
      formButtons: formButtons(this.handleSubmit, this.handleClose)
    }
  },
  watch: {
    visible() {
      if (this.visible && this.modalFormData.rightDataType) {
        this.handleRadioChange(this.modalFormData.rightDataType)
        this._createFormItem()
      }
    }
  },
  methods: {
    handleRadioChange(e) { // radio 改变
      let orgIsHide = true
      let deptIsHide = true
      if (e === 2) {
        orgIsHide = false
      } else if (e === 3) {
        deptIsHide = false
      }
      this.orgIsHide = orgIsHide
      this.deptIsHide = deptIsHide
      this._createFormItem()
    },

    handleSubmit(values) {
      const rightDataType = values.rightDataType
      switch (rightDataType) {
        case 1:
          values.deptIds = ''
          values.orgIds = ''
          break
        case 2:
          values.deptIds = ''
          values.orgIds = values.orgIdList.join(',')
          break
        case 3:
          values.orgIds = ''
          values.deptIds = values.deptIdList.join(',')
          break
        default:
          this.$message.warning('请选择数据权限范围!')
          return false
      }
      this.$emit('handleSubmit', values)
    },

    handleClose() {
      this.$emit('update:visible', false)
    },

    _createFormItem() {
      this.renderFormItem = dataAuthFormItem(this.handleRadioChange, this.orgList, this.deptDropList, this.orgIsHide, this.deptIsHide)
    },

    postDeptFindPage(orgId) { // 获取列表
      this.orgId = orgId
      fetchDropDeptAllList({ orgId }).then(res => {
        this.deptDropList = res.records.map(item => ({ key: item.id, value: item.name }))
        this._createFormItem()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
